package com.csj.mvvm.algorithm

import android.text.TextUtils

object RC4Util {
    /**
     * @param keys 加密的密钥
     * @param encrypt 待加密的数据
     */
    fun RC4(keys: String, encrypt: String): String {
        if (TextUtils.isEmpty(keys) || TextUtils.isEmpty(encrypt)) {
            return ""
        }
        val keyBytes = CharArray(256)
        val cypherBytes = CharArray(256)
        for (i in 0..255) {
            keyBytes[i] = keys[i % keys.length]
            cypherBytes[i] = i.toChar()
        }
        var jump = 0
        for (i in 0..255) {
            jump = jump + cypherBytes[i].code + keyBytes[i].code and 0xFF
            val tmp = cypherBytes[i] // Swap:
            cypherBytes[i] = cypherBytes[jump]
            cypherBytes[jump] = tmp
        }
        var i = 0
        jump = 0
        var Result = ""
        for (element in encrypt) {
            i = i + 1 and 0xFF
            val tmp = cypherBytes[i]
            jump = jump + tmp.code and 0xFF
            val t = (tmp.code + cypherBytes[jump].code and 0xFF).toChar()
            cypherBytes[i] = cypherBytes[jump] // Swap:
            cypherBytes[jump] = tmp
            try {
                Result += String.format("%02x", element.code xor cypherBytes[t.code].code)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        return Result
    }
}